package service.impl;

import dao.UserDAO;
import dao.impl.UserDAOImpl;
import pojo.UserDO;
import service.UserService;

public class UserServiceImpl implements UserService {
    private  UserDAOImpl userDAO = new UserDAOImpl();
    @Override
    public UserDO getByUserNameAndPwd(String username, String pwd) {
        return userDAO.getByUsernameAndPwd(username,pwd);
    }

    @Override
    public void saveMoney(int id, int blance) throws Exception {
        if (blance<0){
            throw new Exception("请输入正确金额");
        }
        UserDO user = userDAO.getById(id);
        user.setBalance(user.getBalance()+blance);
        userDAO.getConnection();
        userDAO.update(user);
        userDAO.close(userDAO.getCon(),userDAO.getStatement());
    }

    @Override
    public void getMoney(int id, int blance) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getBalance()<blance){
            throw new Exception("余额不足");
        }
        user.setBalance(user.getBalance()-blance);
        userDAO.getConnection();
        userDAO.update(user);
        userDAO.close(userDAO.getCon(),userDAO.getStatement());
    }

    @Override
    public int searchMoney(int id) {
        UserDO user = userDAO.getById(id);
        return  user.getBalance();
    }

    @Override
    public void exchangMoney(int id, String name, int money) throws Exception {
        UserDO user = userDAO.getById(id);
        UserDO user2 = userDAO.getByName(name);
        System.out.println(user2);
        if (user2==null){
            throw new Exception("查无此人");
        }
        if (user.getId() == user2.getId()){
            throw new Exception("不能转账给自己");
        }
        if (user.getBalance() < money){
            throw new Exception("金额不足");
        }
        try {
            user.setBalance(user.getBalance() - money);
            user2.setBalance(user2.getBalance() + money);
            userDAO.getConnection();
            userDAO.setAutocommit(false);
            userDAO.update(user);
            userDAO.update(user2);
            userDAO.commit();
        } catch (Exception e) {
            userDAO.rollback();
            e.printStackTrace();
        } finally {
            userDAO.close();
        }

    }

    @Override
    public void changpw (UserDO userDo) {
        userDAO.update(userDo);
    }


}
